<template>
  <div class="login">
    <div class="login-content">
      <div class="login-logo">
        <p>巡检维护管理平台</p>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title">账户登录</h3>
        <el-form-item label="组织" prop="deptCode">
          <el-select v-model="loginForm.deptCode" :disabled="loginForm.disabled" @change="$forceUpdate()" placeholder="请选择">
            <template slot="prefix">
              <img src="@/assets/images/depth.png" alt="">
            </template>
            <el-option
              v-for="(item, index) in deptList"
              :key="index"
              :label="item.deptName"
              :value="item.deptCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账户" prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="账号"
            @input="inputChange"
          >
            <template slot="prefix">
              <img src="@/assets/images/username.png" alt="">
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            @keyup.enter.native="handleLogin"
            auto-complete="off"
            placeholder="密码"
            v-model="loginForm.password"
            :type="showPassword ? 'text' : 'password'"
          >
          <template slot="prefix">
            <img src="@/assets/images/password.png" alt="">
          </template>
          <i slot="suffix" class="eyes" @click="switchPassword">
            <img
              v-if="showPassword"
              class="input_icon"
              src="../assets/images/eye.png"
            />
            <img
              v-else
              class="input_icon"
              src="../assets/images/eye-close.png"
            />
          </i>
          </el-input>
        </el-form-item>
        <!-- <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item> -->
        <div class="rememberMe">
          <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住账户密码</el-checkbox>
        </div>
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div class="checkbox-form">
            <el-checkbox v-model="loginForm.check" style="margin:0px 0px 25px 0px;">
              <p class="label-from">登录即表示同意<label @click="openDoc">《用户服务协议》</label>、<label @click="openDoc">《隐私协议》</label></p>
            </el-checkbox>
          </div>
          <!-- <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div> -->
        </el-form-item>
      </el-form>
    </div>  
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { listDept1 } from "@/api/system/dept";

const validateUser = (rule, value, callback) => {
  var reg = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g;
  if (value === '') {
    callback(new Error('账号是必填项！'))
  } else if (reg.test(value)) {
    callback(new Error("仅限输入大小写字母、数字、特殊字符！"))
  } else if (/\s/g.test(value) || value.indexOf(' ') >= 0) {
    callback(new Error("仅限输入大小写字母、数字、特殊字符！"))
  } else {
    callback()
  }
}

const validatePass = (rule, value, callback) => {
  var reg = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g;
  if (value === '') {
    callback(new Error('密码是必填项！'))
  } else if (reg.test(value)) {
    callback(new Error("仅限输入大小写字母、数字、特殊字符！"))
  } else if (/\s/g.test(value) || value.indexOf(' ') >= 0) {
    callback(new Error("仅限输入大小写字母、数字、特殊字符！"))
  } else {
    callback()
  }
}

export default {
  name: "Login",
  data() {
    return {
      showPassword: false,
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        deptCode: "",
        rememberMe: false,
        code: "",
        uuid: "",
        check: false,
        disabled: false
      },
      loginRules: {
        username: [
          { required: true, validator: validateUser, trigger: "change" }
        ],
        password: [
          { required: true, validator: validatePass, trigger: "change" }
        ],
        deptCode: [{ required: true, trigger: "blur", message: "请选择机构" }]
        // code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      deptList: []
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    // this.getCode(); // 获取验证码图片
    this.getList();
  },
  methods: {
    switchPassword() {
      this.showPassword = !this.showPassword;
    },
    /** 查询部门列表 */
    getList() {
      listDept1({show: 1, status: 0}).then(response => {
        this.deptList = response.data
        this.getCookie();
      });
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      const deptCode = Cookies.get('deptCode')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        deptCode: deptCode === undefined ? this.loginForm.deptCode : deptCode
      };
      this.inputChange()
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        console.log(this.loginForm)
        if (valid) {
          if (!this.loginForm.check) {
            return this.$message.error('请同意《用户服务协议》及《隐私协议》')
          }
          this.loading = true;
          if (this.loginForm.rememberMe) {
            if (this.loginForm.username === 'superadmin') {
              Cookies.set("username", this.loginForm.username, { expires: 30 });
              Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
              Cookies.set("deptCode", "", { expires: 30 });
              Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
            } else {
              Cookies.set("username", this.loginForm.username, { expires: 30 });
              Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
              Cookies.set("deptCode", this.loginForm.deptCode, { expires: 30 });
              Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
            }
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("deptCode");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$store.dispatch('GetInfo').then(res => {
                // 拉取完user_info信息
                const roles = res.roles
                this.$store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
                  // 根据roles权限生成可访问的路由表
                  // console.log(accessRoutes, from, to.fullPath)
                  console.log(accessRoutes, '!!!!!!')
                  var heardPath=accessRoutes[0].path.split("/")[1]==''?"":accessRoutes[0].path;
                  this.$router.addRoutes(accessRoutes) // 动态添加可访问路由表
                  let pathIndex = ''
                  if (accessRoutes[0].children && accessRoutes[0].children.length) {
                    pathIndex = heardPath + '/' + accessRoutes[0].children[0].path
                  } else {
                    pathIndex = heardPath
                  }
                  // console.log(this.redirect, pathIndex)
                  // 1、this.redirect == undefined,主要针对直接从http://172.16.6.205:9090/login，登入系统。
                  // 2、this.redirect == '/'，主要针对直接从这个http://172.16.6.205:9090/login?redirect=%2F，登入系统。因为没有设置重定向的路由
                  // 如果登录的时候出现1、2两种情况，那么就跳到路由的第一个路由页面，如果登录的时候，有设置可以访问的重定向地址，那么登录后就跳到重定向地址。
                  if (pathIndex != '') {
                    this.$router.push({ path: pathIndex  }).catch(() => {}) 
                    //this.$router.push({ path: this.redirect == '/' || this.redirect == undefined ? pathIndex : this.redirect }).catch(() => {}) // 跳转重定向页面或跳到默认首页indexPage
                  }
                })
              })
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    },
    openDoc() {
      window.open('http://183.134.199.132:8088/doc/doc.txt', '_blank')
    },
    // 验证superadmin并禁用组织下拉
    inputChange(val) {
      if (!val) return
      if (this.loginForm.username === 'superadmin') {
        this.deptList.push({
          deptName: '杭州起域科技有限公司',
          deptCode: '91330183MA2KD9B04H'
        })
        this.$set(this.loginForm, 'deptCode', '91330183MA2KD9B04H')
        this.loginForm.disabled = true
      } else {
        this.deptList = this.deptList.filter(item => item.deptCode !== '91330183MA2KD9B04H')
        let deptCode = this.loginForm.deptCode === '91330183MA2KD9B04H' ? '' : this.loginForm.deptCode
        this.$set(this.loginForm, 'deptCode', deptCode)
        this.loginForm.disabled = false
      }
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  
  .el-form-item {
    margin-bottom: 10px;
  }
  .el-form-item--medium .el-form-item__label {
    color: #fff;
  }
  .el-checkbox__label, .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #fff;
  }
  .el-button--primary {
    height: 56px;
    background: linear-gradient(270deg, rgba(0,147,252,0.6) 0%, #3C7EFF 100%);
    border-radius: 10px;
  }
  .el-select {
    width: 100%;
  }
  .login-form .el-input input {
    border-radius: 10px;
  }
}
.login-content {
  width: 1066px;
  height: 543px;
  display: flex;
  .login-logo {
    width: 670px;
    height: 100%;
    background: url('../assets/images/banner.png') no-repeat;
    background-size: 100% 100%;
    p {
      margin: 24px 0 0 40px;
      font-size: 36px;
      color: #FFFFFF;
      line-height: 56px;
    }
  }
}
.title {
  margin: 0px auto 30px auto;
  text-align: left;
  font-size: 24px;
  color: #FFFFFF;
  line-height: 33px;
}

.login-form {
  border-radius: 0px 8px 8px 0px;
  background: #33A1FD;
  width: 396px;
  padding: 50px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .el-input__prefix {
    display: flex;
    align-items: center;
    margin-left: 6px;
  }
  .el-input--prefix .el-input__inner {
    padding-left: 36px;
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
  .checkbox-form {
    width: 100%;
    display: flex;
  }
  .label-from {
    width: 100%;
    text-align: center;
    font-weight: 400;
    font-size: 12px;
    color: #FFFFFF;
    line-height: 18px;
    text-align: center;
    font-style: normal;
    label {
      font-weight: 400;
      font-size: 12px;
      color: #FFFFFF;
      line-height: 20px;
      text-align: left;
      font-style: normal;
      text-decoration-line: underline;
      cursor: pointer;
    }
  }
  .rememberMe {
    margin-top: 18px;
  }
  .el-checkbox__inner {
    background: transparent;
  }
  .el-select .el-input .el-select__caret {
    color: #000000;
  }
  .el-icon-arrow-up:before {
    content: "";
    background: url('../assets/images/select-icon.png') no-repeat center center;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) rotate(180deg);
  }
  .el-checkbox__input.is-focus .el-checkbox__inner {
    border-color: #fff !important;
  }
  .el-checkbox__input.is-checked .el-checkbox__inner {
    border-color: #1890ff !important;
  }
  .eyes {
    height: 100%;
    display: flex;
    align-items: center;
    cursor: pointer;
    img {
      width: 18px;
      height: 18px;
    }
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
